﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CDFWPUG.Model;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using WP7Contrib.Collections;
using Microsoft.Phone.Shell;
using WP7Contrib.Services.BingMaps;
using System.Collections.Generic;

namespace CDFWPUG.Helpers
{
    public class MeetingHelper
    {


        public static Meeting GetMeeting(string xml)
        {
            XElement xmlApps = XElement.Parse(xml);
            Meeting nextMeeting = (from item in xmlApps.Descendants("meeting")
                                   select new Meeting
                                   {
                                       Title = item.Element("title").Value,
                                       Description = item.Element("description").Value,
                                       Date = item.Element("date").Value,
                                       Time = item.Element("time").Value,
                                       Type = item.Element("type").Value,
                                       Agenda = (from a in item.Descendants("agenda")
                                                select new AgendaItem
                                                {
                                                    Time = a.Element("time").Value,
                                                    Title = a.Element("title").Value,
                                                    Description = a.Element("description").Value
                                                    
                                                }).ToList(),



                                   }).First();
            return nextMeeting;

        }

        public static Meeting GetMeetingInfo(int id)
        {
            var results = GetMeetingsFromIsolatedStorage();
            return (from a in results where a.ID == id 
                        select a).First();

        }

        public static ObservableCollection<Meeting> Test_GetUpcomingMeetings(int count)
        {
            ObservableCollection<Meeting> list;
            var resource = System.Windows.Application.GetResourceStream(new Uri("Data/Meetings.xml", UriKind.Relative));
            StreamReader streamReader = new StreamReader(resource.Stream);
            string xml = streamReader.ReadToEnd();
            var items = ParseMeetings(xml);
            list = new ObservableCollection<Meeting>(items.Take(count));
            return list;
        }

        public static void CreateSecondaryTile(Meeting meeting)
        {
            double lat = meeting.MeetingVenue.Latitude;
            double lon = meeting.MeetingVenue.Longitude;
            string strURi = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/{0},{1}/15?mapSize=190,190&&key={2}",lat, lon, App.BingApiKey); 
            ShellTile secondaryTile =
                ShellTile.ActiveTiles.FirstOrDefault(
                x => x.NavigationUri
                    .ToString()
                    .Contains("pageMeeting.xaml?MeetingID=" + meeting.ID));

            if (secondaryTile == null)
            {
                StandardTileData NewTileData = new StandardTileData
                {
                    BackgroundImage = new Uri(strURi, UriKind.Absolute),
                    Title = String.Format("{0} Meeting", meeting.MeetingVenue.Town),
                    Count = 0,
                    BackBackgroundImage = new Uri(String.Empty , UriKind.Relative),
                    BackTitle = meeting.MeetingVenue.Title,
                    BackContent = meeting.Date,
                };

                ShellTile.Create(new Uri("/Views/pageMeeting.xaml?MeetingID=" + meeting.ID, UriKind.Relative), NewTileData);

            }
        }

        public static ObservableCollection<Meeting> GetMeetingsFromIsolatedStorage()
        {
            string xml = Helpers.IsolatedStorageHelper.LoadFile("Meetings.xml");
            var results = ParseMeetings(xml);
            return results;
        }

        public static ObservableCollection<Meeting>  ParseMeetings(string xml)
        {

            XElement xmlApps = XElement.Parse(xml);
            var items = (from item in xmlApps.Descendants("meeting")
                         select new Meeting
                         {
                             ID = Convert.ToInt32(item.Element("id").Value),
                             Title = item.Element("title").Value,
                             Description = item.Element("description").Value,
                             Date = item.Element("date").Value,
                             Time = item.Element("time").Value,
                             Type = item.Element("type").Value,
                             Agenda = (from a in item.Descendants("agenda")
                                       select new AgendaItem
                                       {
                                           Time = a.Element("time").Value,
                                           Title = a.Element("title").Value,
                                           Description = a.Element("description").Value

                                       }).ToList(),

                             MeetingVenue = new Address
                             {
                                 Title = (from a in item.Descendants("venue")
                                          select a).First().Element("name").Value,
                                 PostCode = (from a in item.Descendants("venue")
                                             select a).First().Element("postcode").Value,
                                 Town = (from a in item.Descendants("venue")
                                         select a).First().Element("town").Value,
                                 Address1 = (from a in item.Descendants("venue")
                                             select a).First().Element("address1").Value,
                                 Address2 = (from a in item.Descendants("venue")
                                             select a).First().Element("address2").Value,
                                 County = (from a in item.Descendants("venue")
                                           select a).First().Element("county").Value,
                                 Latitude = Convert.ToDouble((from a in item.Descendants("venue")
                                                              select a).First().Element("latitude").Value),
                                 Longitude = Convert.ToDouble((from a in item.Descendants("venue")
                                                               select a).First().Element("longitude").Value),
                                 Telephone = (from a in item.Descendants("venue")
                                              select a).First().Element("telephone").Value,
                                 Website = (from a in item.Descendants("venue")
                                            select a).First().Element("website").Value



                             }

                         });



            return new ObservableCollection<Meeting>(items);

        }

        public static string GetMeetingMessage(Meeting meeting)
        {
            string message = string.Format("WPUG Meeting: {0} {1} at {2}, {3}", meeting.Date, meeting.Time, meeting.MeetingVenue.Title, meeting.MeetingVenue.PostCode );
            return message;
        }
    }
}
